<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      ref="crud"
      :search.sync="query"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button size="small" icon="el-icon-view" type="text" @click="rowView(row)">详情</el-button>
        <el-button size="small" type="text" @click="handleViewOtherInfo(row)">其他信息</el-button>
      </template>
      <template slot="sequenceDefinitionSubTypeSearch">
        <el-select v-model="query.sequenceDefinitionSubType" placeholder="请选择业务小类" :clearable="true">
          <el-option v-for="cateItem in subTypeList" :key="cateItem.value" :label="cateItem.label" :value="cateItem.value"> </el-option>
        </el-select>
      </template>
    </avue-crud>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>

    <el-dialog append-to-body @close="closeDetailModel" v-if="detailModal" class="detail" :visible.sync="detailModal" title="详情" width="60%" top="5vh">
      <avue-crud
        ref="crud"
        :table-loading="detailLoading"
        :data="detailData"
        :option="detailOption"
        :page.sync="detailPage"
        @current-change="currentDetailChange"
        @size-change="sizeDetailChange"
      >
        <template slot="sequenceNumber" slot-scope="{ row }">
          <div class="sequenceNumber">
            <!-- <img v-if="row.status == 4 && form.type == 'MATERIAL'" style="position: absolute; width: 39px; height: 39px; right: 0; top: 0" src="/img/bg/zuofei.png" /> -->
            <span>{{ row.sequenceNumber }}</span>
          </div>
        </template>
      </avue-crud>
    </el-dialog>

    <view-other-info :visible.sync="printDialog" :other-info-option="viewOtherInfo" :other-info="otherInfo"></view-other-info>
  </basic-container>
</template>
<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import CommonPrintersTemplate from '@/components/common-printers-template/common-printers-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import { getOtherInfoConfig, getPage } from '@/api/labelManagement/printRecord';
import { getSeqNoRules, subTypeMap } from '@/util/global';
import { getList, getPackingDetail, getProductDetail, getPrinter, getLabelDetail } from '@/api/admin/barcode-record';
import { mapGetters } from 'vuex';
import { getCategory } from '@/api/warehouse/materialRules';
import viewOtherInfo from '@/views/labelManagement/components/viewOtherInfo';

export default {
  name: 'AdminBarcodeRecord',
  components: {
    CommonModalTemplate,
    CommonPrintersTemplate,
    userTableConfig,
    viewOtherInfo
  },
  mixins: [userConfig()],
  data() {
    return {
      otherInfo: {},
      viewOtherInfo: {
        submitBtn: false,
        emptyBtn: false,
        detail: true,
        column: []
      },
      printDialog: false,
      pageCode: 'ADMIN_BARCODE_RECORD',
      form: {},
      query: {},
      loading: true,
      title: '',
      detailLoading: false,
      detailModal: false,
      flagType: false,
      scrapData: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      detailData: [],
      data: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 5,
        border: true,
        index: true,
        addBtn: false,
        delBtn: false,
        viewBtn: false,
        viewBtnText: '详情',
        viewTitle: '详情',
        editBtn: false,
        selection: false,
        dialogClickModal: false,
        indexLabel: '序号',
        menuWidth: 150,
        columnBtn: false,
        labelWidth: 200,
        column: [
          {
            label: '大类',
            prop: 'sequenceDefinitionType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=dalei',
            cascader: ['sequenceDefinitionSubType'],
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            change: ({ column, value }) => {
              this.getSubTypeData(value);
            },
            search: true
          },
          {
            label: '小类',
            prop: 'sequenceDefinitionSubType',
            // dicUrl: '/api/blade-system/dict/dictionary?code={{key}}',
            // props: {
            //   label: 'dictValue',
            //   value: 'dictKey'
            // },
            formatter: (row) => {
              return subTypeMap[row.sequenceDefinitionSubType] || '';
            },
            fromslot: true,
            type: 'select',
            search: true
          },
          {
            label: '单据号',
            prop: 'orderNo',
            search: true,
            width: 200
          },
          {
            label: '物料编码',
            prop: 'partNo',
            searchSpan: 6,
            search: true
          },
          {
            label: '序列号规则',
            prop: 'sequenceNumberFormat',
            width: 200
          },

          {
            label: '起始条码流水号',
            prop: 'sequenceNumberFrom',
            width: 200
          },
          {
            label: '结束条码流水号',
            prop: 'sequenceNumberTo',
            width: 200
          },
          {
            label: '数量',
            prop: 'printQuantity'
          },
          {
            label: '标签模板',
            prop: 'labelTemplateName'
          },
          {
            label: '操作端',
            prop: 'terminal'
          },
          {
            label: '打印类型',
            prop: 'printType',
            type: 'select',
            search: true,
            dicData: [
              { label: '重打', value: 'REPEAT' },
              { label: '首次', value: 'FIRST' }
            ]
          },
          {
            label: '打印人',
            prop: 'name'
          },
          {
            label: '打印时间',
            prop: 'createTime'
          },
          {
            label: '打印机',
            prop: 'equipmentName'
          },
          {
            label: '登录电脑',
            prop: 'computer'
          },
          {
            label: '备注',
            prop: 'remark'
          },
          {
            label: '序列号',
            prop: 'sequenceNumber',
            hide: true,
            search: true
          },
          {
            label: '打印时间',
            prop: 'datetimerange',
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            search: true,
            searchSpan: 12,
            hide: true
          }
        ]
      },
      detailOption: {
        addBtn: false,

        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        delBtn: false,
        viewBtn: false,
        editBtn: false,
        selection: false,
        refreshBtn: false,
        menu: false,
        dialogClickModal: false,
        indexLabel: '序号',
        column: [
          {
            label: '产品序列号',
            prop: 'sequence',
            slot: true
          }
        ]
      },
      tableOption: {},
      printInfo: {},
      timer: new Date().getTime(),
      modalName: '',
      sourceType: '',
      subTypeList: []
    };
  },
  computed: {
    ...mapGetters(['permission', 'userInfo'])
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    searchChange(params, done) {
      if (params.datetimerange && params.datetimerange.length > 0) {
        params.startTime = params.datetimerange[0];
        params.endTime = params.datetimerange[1];
        delete params.datetimerange;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentDetailChange(currentPage) {
      this.detailPage.currentPage = currentPage;
      this.getDetail();
    },
    sizeDetailChange(pageSize) {
      this.detailPage.pageSize = pageSize;
      this.getDetail();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      //   this.loading = false;
      //   this.data = [{ barCodeType: '', barCodeRule: '123' }];
      this.loading = true;
      getPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // [] || dataListTable
        this.data = this._map(data.records, (item) => {
          return {
            ...item,
            sheetNo: item.sheetNo || item.orderNo
          };
        });
        this.loading = false;
        //   this.selectionClear();
      });
    },
    async getSubTypeData(val) {
      try {
        const res = await getCategory({ code: val });
        this.subTypeList = (res.data.data || []).map((item) => ({
          label: item.dictValue,
          value: item.dictKey
        }));
      } catch (e) {
        console.warn(e);
      }
    },
    async getDefaultPrinter() {
      const { user_id } = this.userInfo;
      try {
        const res = await getPrinter({ id: user_id });
        return res.data.data;
      } catch (e) {
        console.warn(e);
      }
    },
    closeDetailModel() {
      this.detailModal = false;
      this.detailData = [];
      this.detailPage = {
        pageSize: 20,
        currentPage: 1,
        total: 0
      };
    },
    async handleViewOtherInfo(row) {
      try {
        const res = await getOtherInfoConfig(row.labelTemplateId);
        const data = res.data.data;
        if (data.fieldList && data.fieldList.length) {
          const column = [];
          data.fieldList.forEach((item) => {
            const obj = {};
            obj.type = item.controlType;
            obj.label = item.name;
            obj.value = item.defaultValue;
            obj.prop = item.field;
            if (item.isRequired) {
              obj.rules = [
                {
                  required: true,
                  message: `请选择${item.name}`
                }
              ];
            }
            if (item.controlType === 'date') {
              obj.format = 'yyyy-MM-dd';
              obj.valueFormat = 'yyyy-MM-dd';
            } else if (item.controlType === 'datetime') {
              obj.format = 'yyyy-MM-dd HH:mm:ss';
              obj.valueFormat = 'yyyy-MM-dd HH:mm:ss';
            }
            column.push(obj);
          });
          this.$set(this.viewOtherInfo, 'column', column);
          this.otherInfo = JSON.parse(row.printInput);
          this.printDialog = true;
        } else {
          this.$message.warning('该打印记录无打印时输入字段');
        }
      } catch (e) {
        console.warn(e);
      }
    },
    rowView(row) {
      this.form = row;
      this.getDetail();
    },
    getDetail() {
      this.detailLoading = true;
      if (!this.form.sequenceGenerationId) {
        this.$message.warning('该打印记录无详情信息');
        return;
      }
      getLabelDetail(this.detailPage.currentPage, this.detailPage.pageSize, { id: this.form.sequenceGenerationId }).then((res) => {
        const data = res.data.data;
        this.detailData = data.records;
        this.detailPage.total = data.total;
        this.detailLoading = false;
      });
      this.detailModal = true;
    },
    closeScrapModel() {
      this.$refs.scrapForm.resetForm();
    },
    closeSubstitution() {
      this.substitutionModel = false;
      this.$refs.substitutionForm.resetFields();
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style scoped lang="scss">
.menu-option {
  text-align: left;
  padding: 0 30px;
}
.sequenceNumber {
  position: relative;
  padding: 8px 0 8px 0;
}
.detail {
  ::v-deep .el-table--small td {
    padding: 0;
  }
  ::v-deep .el-table .cell {
    padding: 0 0 0 8px;
  }
}
</style>
